/*
 * RollingAvg.cpp
 *
 *  Created on: Jan 26, 2013
 *      Author: Drew Prevost
 */

#include "RollingAvg.h"

RollingAvg::RollingAvg()
{
  reset();
}

void RollingAvg::_refreshAverage()
{
  if ( nCurIndex > 0 && bCurAvgDirty )
  {
    double nTotal = 0.0;
    for ( unsigned int nIndex = 0; nIndex < nCurIndex; nIndex++ )
    {
      nTotal += arrHistory[nIndex];
    }

    nCurAvg = ( nTotal / (double) nCurIndex );
    bCurAvgDirty = false;
  }
}

double RollingAvg::getAverage()
{
  _refreshAverage();
  return nCurAvg;
}

double RollingAvg::getLast()
{
  return nLast;
}

void RollingAvg::add( double nNewValue )
{
  if ( nCurIndex >= NUM_HISTORY_ENTRIES )
  {
    // I've filled up the array so I need to shift everything up and add the new value to the end
    for ( unsigned int nIndex = 0; nIndex < ( NUM_HISTORY_ENTRIES - 1 );
        nIndex++ )
    {
      arrHistory[nIndex] = arrHistory[nIndex + 1];
    }

    arrHistory[NUM_HISTORY_ENTRIES - 1] = nNewValue;
  }
  else
  {
    // still filling up array, so we need to add the new value and increment nCurIndex
    arrHistory[nCurIndex] = nNewValue;
    nCurIndex++;
  }

  nLast = nNewValue;
  bCurAvgDirty = true;
}

void RollingAvg::reset()
{
  nCurIndex = 0;
  nCurAvg = 0.0;
  bCurAvgDirty = false;
  nLast = 0.0;
}
